import {ref, watchEffect} from 'vue'
// 缓存操作
const todoStorage = {
    fetch() {
        let todoList = JSON.parse(localStorage.getItem('vue3-todos') || '[]')
        todoList.forEach((todo, index) => {
            todo.id = index + 1
        })
        return todoList
    },
    save(todoList) {
        localStorage.setItem('vue3-todos', JSON.stringify(todoList))
    }
}


export default function useTodos(state) {
    const todoList = ref(todoStorage.fetch())

    function addTodo() {
        todoList.value.push({
            id: todoList.value.length + 1,
            title: state.newTodo,
            completed: false
        })
        state.newTodo = ''
    }

    function removeTodo(item) {
        let index = todoList.value.indexOf(item)
        todoList.value.splice(index, 1)
    }

    watchEffect(() => {
        todoStorage.save(todoList.value)
    })

    return {todoList, removeTodo, addTodo}
}

